import 'package:get/get.dart';
import 'package:flutter/foundation.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/mixins/user_profile_mixin.dart';
import '../../../common/routers/names.dart';
import '../../../common/utils/index.dart';

class ShenbaoAssessmentController extends GetxController with UserProfileMixin {
  ShenbaoAssessmentController();

  // 🔥 状态管理
  var isLoading = false.obs;
  var projectList = <ProjectModel>[].obs;
  var errorMessage = ''.obs;
  
  // 🗳️ 投票选举相关状态管理
  final isLoadingVote = false.obs;
  final hasVoted = false.obs;
  final expertNum = 0.obs;
  final votedNum = 0.obs;
  final electedLeaderId = 0.obs;
  final selectedExpertId = 0.obs;
  final voteErrorMessage = ''.obs;
  final voteSheetType = ''.obs;
  final currentProjectId = 0.obs;
  final RxList<ProjectExpert> projectExperts = <ProjectExpert>[].obs;

  // 🔥 获取当前登录专家的ID（从UserProfileMixin）
  int get currentExpertId {
    final expertIdStr = expertId; // 从UserProfileMixin获取String类型的expertId
    final parsedId = int.tryParse(expertIdStr);
    
    if (parsedId == null || parsedId <= 0) {
      debugPrint('⚠️ 专家ID无效: $expertIdStr，使用默认值1');
      return 1; // 如果解析失败，使用默认值
    }
    
    debugPrint('✅ 使用专家ID: $parsedId');
    return parsedId;
  }

  /// 初始化数据
  _initData() {
    loadProjectList();
    update(["shenbao_assessment"]);
  }

  /// 加载项目列表（评审人项目 flag=0）
  Future<void> loadProjectList() async {
    try {
      debugPrint('🔄 申报评估页面 - 开始加载项目列表');
      
      // 检查登录状态
      if (!isLoggedIn) {
        debugPrint('❌ 用户未登录，无法加载项目列表');
        errorMessage.value = '请先登录';
        return;
      }
      
      isLoading.value = true;
      errorMessage.value = '';
      
      final expertIdToUse = currentExpertId;
      debugPrint('🔄 使用专家ID: $expertIdToUse 获取评审项目列表');
      
      // 调用API获取评审人项目列表
      final projects = await ProjectApi.getProjectList(
        expertId: expertIdToUse,
        flag: 0, // 0-作为评审人的项目列表
      );
      
      projectList.value = projects;
      
      debugPrint('✅ 申报评估页面 - 专家 $expertIdToUse 加载了 ${projects.length} 个项目');
      
      // 📋 输出每个项目的ID、名称和状态
      if (projects.isNotEmpty) {
        debugPrint('📋 项目列表详情：');
        for (var i = 0; i < projects.length; i++) {
          final project = projects[i];
          final statusText = ProjectModel.getStatusTextByValue(project.status);
          debugPrint('  ${i + 1}. 项目ID: ${project.id}, 项目名称: ${project.projectName}');
          debugPrint('     状态: $statusText (status=${project.status})');
        }
      }
      
    } catch (e) {
      debugPrint('❌ 申报评估页面 - 加载项目列表失败: $e');
      errorMessage.value = e.toString();
      projectList.value = [];
    } finally {
      isLoading.value = false;
      update(["shenbao_assessment"]);
    }
  }

  /// 刷新项目列表
  Future<void> refreshProjectList() async {
    await loadProjectList();
  }

  /// 点击项目项 - 开始评审
  Future<void> onProjectTap(ProjectModel project) async {
    debugPrint('🔍 点击项目: ${project.projectName}');
    if (project.id == null) {
      debugPrint('⚠️ 项目ID为空，无法开始评审');
      return;
    }
    
    currentProjectId.value = project.id!;
    
    // 检查投票状态
    await checkVoteStatusAndShow();
  }
  
  /// 检查投票状态并设置要显示的弹出框类型
  Future<void> checkVoteStatusAndShow() async {
    if (currentProjectId.value <= 0) return;
    
    try {
      isLoadingVote.value = true;
      voteErrorMessage.value = '';
      voteSheetType.value = '';
      
      debugPrint('🔍 检查投票状态...');
      
      // 先加载专家列表
      await _loadProjectExperts();
      
      // 1. 检查当前专家是否已投票
      final voted = await UserApi.checkVoted(
        projectId: currentProjectId.value,
        voterId: currentExpertId,
        voteFlag: 0, // 0-评审
      );
      hasVoted.value = voted;
      
      // 2. 获取投票统计信息
      final voteStats = await UserApi.getVoteNum(
        projectId: currentProjectId.value,
        voteFlag: 0, // 0-评审
      );
      expertNum.value = voteStats['expertNum'] ?? 0;
      votedNum.value = voteStats['votedNum'] ?? 0;
      
      debugPrint('📊 投票状态: 已投票=$voted, 专家总数=${expertNum.value}, 已投票数=${votedNum.value}');
      
      // 3. 判断投票是否全部完成
      final allVoted = votedNum.value >= expertNum.value && expertNum.value > 0;
      
      if (allVoted) {
        // 投票已完成，获取当选组长
        final leaderId = await UserApi.getMostVotesExpertId(
          projectId: currentProjectId.value,
          voteFlag: 0, // 0-评审
        );
        electedLeaderId.value = leaderId;
        
        debugPrint('🏆 投票已完成，当选组长ID: $leaderId');
      }
      
      // 4. 根据状态设置弹出框类型
      if (!voted) {
        debugPrint('📋 设置显示投票选举界面');
        voteSheetType.value = 'election';
      } else if (!allVoted) {
        debugPrint('📊 设置显示投票进度');
        voteSheetType.value = 'progress';
      } else {
        debugPrint('🎉 设置显示选举结果');
        voteSheetType.value = 'result';
      }
      
    } catch (e) {
      debugPrint('❌ 检查投票状态失败: $e');
      voteErrorMessage.value = e.toString().replaceAll('Exception: ', '');
      LoadingUtil.error('检查投票状态失败，请重试');
    } finally {
      isLoadingVote.value = false;
    }
  }
  
  /// 加载项目专家列表
  Future<void> _loadProjectExperts() async {
    if (currentProjectId.value <= 0) return;
    
    try {
      debugPrint('👥 开始加载项目专家列表');
      
      final experts = await ProjectApi.getProjectExpertList(
        projectId: currentProjectId.value,
        flag: 0, // 0-评审人专家列表
      );
      
      projectExperts.value = experts;
      debugPrint('✅ 加载项目专家列表成功，共 ${experts.length} 个专家');
      
    } catch (e) {
      debugPrint('❌ 加载项目专家列表失败: $e');
    }
  }
  
  /// 提交投票
  Future<void> submitVote() async {
    if (currentProjectId.value <= 0) return;
    
    if (selectedExpertId.value <= 0) {
      LoadingUtil.info('请选择要投票的专家');
      return;
    }
    
    try {
      LoadingUtil.show('正在提交投票...');
      
      debugPrint('🗳️ 提交投票: 项目ID=${currentProjectId.value}, 选举人=$currentExpertId, 被选举人=${selectedExpertId.value}');
      
      final success = await UserApi.voteTeamLeader(
        projectId: currentProjectId.value,
        voterId: currentExpertId,
        beVotedId: selectedExpertId.value,
        voteFlag: 0, // 0-评审
      );
      
      if (success) {
        debugPrint('✅ 投票成功');
        hasVoted.value = true;
        
        // 关闭当前弹出框
        Get.back();
        
        LoadingUtil.success('投票成功');
        
        // 延迟后重新检查状态并显示进度
        await Future.delayed(const Duration(milliseconds: 500));
        await checkVoteStatusAndShow();
      }
      
    } catch (e) {
      debugPrint('❌ 投票失败: $e');
      LoadingUtil.error('投票失败：${e.toString().replaceAll('Exception: ', '')}');
    }
  }
  
  /// 刷新投票状态
  Future<void> refreshVoteStatus() async {
    if (currentProjectId.value <= 0) return;
    
    try {
      isLoadingVote.value = true;
      
      // 1. 检查当前专家是否已投票
      final voted = await UserApi.checkVoted(
        projectId: currentProjectId.value,
        voterId: currentExpertId,
        voteFlag: 0,
      );
      hasVoted.value = voted;
      
      // 2. 获取投票统计信息
      final voteStats = await UserApi.getVoteNum(
        projectId: currentProjectId.value,
        voteFlag: 0,
      );
      expertNum.value = voteStats['expertNum'] ?? 0;
      votedNum.value = voteStats['votedNum'] ?? 0;
      
      debugPrint('🔄 投票状态已刷新: 已投票=$voted, ${votedNum.value}/${expertNum.value}');
      
      // 3. 如果投票已完成，获取当选组长
      if (votedNum.value >= expertNum.value && expertNum.value > 0) {
        final leaderId = await UserApi.getMostVotesExpertId(
          projectId: currentProjectId.value,
          voteFlag: 0,
        );
        electedLeaderId.value = leaderId;
      }
      
    } catch (e) {
      debugPrint('❌ 刷新投票状态失败: $e');
    } finally {
      isLoadingVote.value = false;
    }
  }
  
  /// 进入评审详情（投票完成后）
  void enterReviewDetail() {
    debugPrint('📝 进入评审详情页');
    
    if (currentProjectId.value <= 0) {
      LoadingUtil.error('项目ID无效');
      return;
    }
    
    // 关闭投票结果弹出框
    Get.back();
    
    // 跳转到详情页
    Get.toNamed(RouteNames.assessmentShenbaoDetail, arguments: {
      'projectId': currentProjectId.value,
    });
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
}
